package com.engr.springbooteasypoi.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;

/**
 * @author : liuYanXin
 * @Description : J.U.C
 * @Date : 2020-03-31
 */
public class ExchangerCls {

    public static void main(String[] args) {
        List<String> buffer1 = new ArrayList<>();
        List<String> buffer2 = new ArrayList<>();

        Exchanger<List<String>> exchanger = new Exchanger<>();

        ProducerTask producer = new ProducerTask(buffer1, exchanger);
        ConsumerTask consumer = new ConsumerTask(buffer2, exchanger);

        Thread thread1 = new Thread(producer);
        Thread thread2 = new Thread(consumer);

        thread1.start();
        thread2.start();
    }
}

class ProducerTask implements Runnable {

    /**
     * 生产者和消费者需要交互的数据
     */
    private List<String> buffer;

    /**
     * 同步生产者和消费者的交换对象
     */
    private final Exchanger<List<String>> exchanger;

    public ProducerTask(List<String> buffer, Exchanger<List<String>> exchanger) {
        this.buffer = buffer;
        this.exchanger = exchanger;
    }

    @Override
    public void run() {

        int cycle = 1;
        for (int i = 0; i < 10; i++) {
            System.out.println("Producer : cycle: " + cycle);
            for (int j = 0; j < 10; j++) {
                String message = "Event " + ((i * 10) + j);
                System.out.println("Producer data: " + message);
                buffer.add(message);
            }
            // 调用exchange()与消费者进行数据交互
            try {
                buffer = exchanger.exchange(buffer);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Producer size: " + buffer.size());
            cycle++;
        }
    }
}

class ConsumerTask implements Runnable {

    private List<String> buffer;

    private final Exchanger<List<String>> exchanger;

    ConsumerTask(List<String> buffer, Exchanger<List<String>> exchanger) {
        this.buffer = buffer;
        this.exchanger = exchanger;
    }

    @Override
    public void run() {
        int cycle = 1;
        for (int i = 0; i < 10; i++) {
            System.out.println("Consumer : Cycle :" + cycle);

            //调用exchange()与消费者进行数据交换
            try {
                buffer = exchanger.exchange(buffer);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Consumer size :" + buffer.size());
            for (int j = 0; j < 10; j++) {
                System.out.println("Consumer get: " + buffer.get(0));
                buffer.remove(0);
            }
            cycle++;
        }
    }
}